import React from 'react';

class TimeInterval extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      interval: this.props.past,
    };
    this.updateInterval = this.updateInterval.bind(this);
  }

  updateInterval() {
    this.setState({
      interval: this.props.past + Date.now() - this.props.beginTime,
    });
    this.timeoutId = setTimeout(this.updateInterval, 1000);
  }

  static format(interval, lang = 'cn') {
    let seconds = Math.floor( (interval/1000) % 60 );
    let minutes = Math.floor( (interval/1000/60) % 60 );
    let hours = Math.floor( (interval/(1000*60*60)) % 24 );
    let days = Math.floor( interval/(1000*60*60*24) );

    let formatTime = '';
    if (days > 0) formatTime += days + (lang === 'cn' ? '天' : ' d ');
    if (hours > 0) formatTime += hours + (lang === 'cn' ? '小时' : ' h ');
    if (minutes > 0 && days === 0) formatTime += minutes + (lang === 'cn' ? '分' : ' min ');
    if (seconds > 0 && days === 0 && hours === 0) formatTime += seconds + (lang === 'cn' ? '秒' : ' s ');
    return lang === 'cn' ? (formatTime === '' ? '0秒前' : formatTime + '前')
      : (formatTime === '' ? '0s ago' : formatTime + 'ago');
  }

  componentDidMount() {
    this.updateInterval();
  }

  componentWillUnmount() {
    clearTimeout(this.timeoutId)
  }

  render() {
    return <span>{TimeInterval.format(this.state.interval, this.props.lang)}</span>
  }
}

export default TimeInterval;
